/*
  @description: 测试老姚的小广告
 * @author: L.Wen
 * @create: 2018-09-29 14:21
 */

import org.openqa.selenium.By;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;

import java.io.BufferedInputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class TestYouliao_3 {

    private static final Logger log = Logger.getLogger(TestYouliao_3.class);

    private static ChromeOptions chromeOptions;

    private WebElement webElement = null;
    private WebElement webElement1 = null;
    private String src;

    private static String proxyUser = "";
    private static String proxyPass = "";

    private static String proxyType = "http";
    private static String proxyAdd;// 芝麻ip

    static {
        //告诉系统chromedriver.exe的位置，打开Chrome浏览器
        System.setProperty("webdriver.chrome.driver", "chromedriver_win32\\chromedriver.exe");
        // 声明ChromeOptions,主要是给Chrome设置参数.
        chromeOptions = new ChromeOptions();
        // 不打开浏览器，直接执行脚本
        chromeOptions.addArguments("--headless");

    }

    /**
     * 打开芝麻代理ip的api连接，获取ip
     * 打开1Call标签
     * 自动执行5次
     */
    @Test(priority = 10, invocationCount = 1)
    public void searchCSDN() throws InterruptedException {

        System.out.println("Test openBD! \n");
        WebDriver driver0;
        driver0 = new ChromeDriver(chromeOptions);
        driver0.manage().window();

        Set<String> windows0 = driver0.getWindowHandles();
        List<String> windowsArr0 = new ArrayList<>(windows0);
        driver0.switchTo().window(windowsArr0.get(0));

        String url_IP =
                "http://webapi.http.zhimacangku.com/getip?num=1&type=1&pro=&city=0&yys=0&port=1&pack=32607&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=";
        driver0.get(url_IP);
        Thread.sleep(3001);
        webElement = driver0.findElement(By.xpath("//body/pre"));
        String address = webElement.getText();
        System.out.println("add: " + address);
        proxyAdd = address;
        driver0.manage().deleteAllCookies();
        driver0.close();
        driver0.quit();
        Thread.sleep(3001);


        // 方法一
        DesiredCapabilities cap = new DesiredCapabilities();
        Proxy proxy = new Proxy();
        proxy.setHttpProxy(proxyAdd).setFtpProxy(proxyAdd).setSslProxy(proxyAdd);
        cap.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);
        cap.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);
        cap.setCapability(CapabilityType.PROXY, proxy);

        // 设置user-agent的参数为手机端
        chromeOptions.addArguments("--user-agent=pixel 2");

        chromeOptions.addArguments("--proxy-type=" + proxyType);

        chromeOptions.addArguments("--proxy=" + proxyAdd);

        cap.setCapability(CapabilityType.PLATFORM, "Android");
        cap.setCapability(CapabilityType.VERSION,"4.4.2");
        cap.setCapability("userAgent","Mozilla/5.0 (Linux; U; Android 4.4.2; zh-cn; PE-TL20 Build/HuaweiPE-TL20) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.3 Mobile Safari/537.36");
        cap.setCapability("User-Agent","Mozilla/5.0 (Linux; U; Android 4.4.2; zh-cn; PE-TL20 Build/HuaweiPE-TL20) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.3 Mobile Safari/537.36");

        WebDriver driver;
        driver = new ChromeDriver(cap);
        driver.manage().window();

        Set<String> windows = driver.getWindowHandles();
        List<String> windowsArr = new ArrayList<>(windows);
        driver.switchTo().window(windowsArr.get(0));


        // 设置默认校验器
        Authenticator.setDefault(new MyAuthenticator(proxyUser, proxyPass));

        // 检验代理成功与否
        driver.get("http://www.baidu.com");
        webElement = driver.findElement(By.xpath("//input[@id = \"kw\"]"));
        webElement.sendKeys("ip");
        webElement = driver.findElement(By.xpath("//*[@id=\"su\"]"));
        webElement.click();
        Thread.sleep(5001);


        // 4.再打开广告测试页
        driver.get("https://youliao.163yun.com/h5/list/?appkey=7a5c4732c2084c54bba26859ad5e9541&secretkey=9630363599734af6872167c54a461ee8&s=semi");
        windows = driver.getWindowHandles();
        windowsArr = new ArrayList<>(windows);
        driver.switchTo().window(windowsArr.get(0));
        System.out.println("Test search1Call! \n");
        Thread.sleep(3001);
        webElement = driver.findElement(By.xpath("//*[@data-key = \"t_0\"]"));
        webElement.click();
        Thread.sleep(3001);

        // 5.打开1Call的第一条链接
        System.out.println("Test clickResult! \n");
        webElement = driver.findElement(By.xpath("//*[@target=\"_blank\"]"));
        webElement.click();
        Thread.sleep(3001);

        // 6.查找广告的超链接
        System.out.println("Test clickAdvertisement! \n");
        Set<String> windows1 = driver.getWindowHandles();
        List<String> windowsArr1 = new ArrayList<>(windows1);
        driver.switchTo().window(windowsArr1.get(1));
//        webElement1 = driver.findElement(By.xpath("//*[@data-id = \"youliao-ad-top-0\"]"));
        webElement1 = driver.findElement(By.xpath("//*[contains(@data-id, 'youliao-ad-')]"));
        webElement1 = webElement1.findElement(By.xpath(".//div[1]/div[1]"));
        Thread.sleep(3001);
        webElement1 = driver.findElement(By.tagName("iframe"));
        src = webElement1.getAttribute("src");
        System.out.println("src: " + src);
        Thread.sleep(3001);

        // 7.打开广告的超链接
        System.out.println("Test openSrc! \n");
        webElement1.click();
        Thread.sleep(3001);

        // 8.打开广告页的第一条链接
        System.out.println("Test clickADResult! \n");
        webElement1 = driver.findElement(By.xpath("//*[@class=\"results\"]"));
        Thread.sleep(3001);
        webElement1 = webElement1.findElement(By.xpath(".//div[1]"));
        webElement1.click();
        Thread.sleep(3001);


        driver.manage().deleteAllCookies();
        driver.close();
        driver.quit();

//        getHtml(src);

    }

    private static String getHtml(String address) {
        StringBuffer html = new StringBuffer();
        String result = null;
        try {
            URL url = new URL(address);
            URLConnection conn = url.openConnection();
//            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");

            try (BufferedInputStream in = new BufferedInputStream(conn.getInputStream())) {
                String inputLine;
                byte[] buf = new byte[4096];
                int bytesRead = 0;
                while (bytesRead >= 0) {
                    inputLine = new String(buf, 0, bytesRead, StandardCharsets.ISO_8859_1);
                    html.append(inputLine);
                    bytesRead = in.read(buf);
                }
                buf = null;
            } finally {
                conn = null;
                url = null;
            }
            result = new String(html.toString().trim().getBytes(StandardCharsets.ISO_8859_1), "gb2312").toLowerCase();
            System.out.println("result: \n" + result);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            html = null;
        }
        return result;
    }


}

/**
 * @description: 重写方法
 * @author: L.Wen
 * @create: 2018-10-18 17:11
 **/
class MyAuthenticator extends Authenticator {
    private String user;
    private String password;

    MyAuthenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password.toCharArray());
    }

}

